<template>
  <div class="flex">
    <div class="tableManage w-100%">
      <ContentWrap>
        <!-- 数据表格 -->
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :columns="allSchemas.tableColumns"
          :data="dataList"
          :loading="loading"
          @register="tableRegister"
          :pagination="{ total }"
        />
      </ContentWrap>
    </div>

    <!-- 新增/编辑/查看对话框 -->
    <Dialog width="65%" v-model="dialogVisible" :title="dialogTitle">
      <!-- 详情组件（查看时显示） -->
      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />
      <!-- 对话框底部按钮 -->
      <template #footer>
        <BaseButton @click="dialogVisible = false">关闭</BaseButton>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="tsx">
import {
  ref,
  unref,
  reactive,
  watch,
  computed,
  onMounted,
  ComponentRef,
} from "vue";
import { ContentWrap } from "@/components/ContentWrap";
import { Table } from "@/components/Table";
import { useTable } from "@/hooks/web/useTable";
import { useValidator } from "@/hooks/web/useValidator";
import Detail from "./components/dComponentsDetail.vue";
import { Dialog } from "@/components/Dialog";
import { CrudSchema, useCrudSchemas } from "@/hooks/web/useCrudSchemas";
import { BaseButton } from "@/components/Button";
import { useDictionaryStore } from "@/store/modules/dictionaryStore";
import {  View } from "@element-plus/icons-vue";

// ============ 初始化Store和工具函数 ============
const { required } = useValidator(); // 表单验证工具
const dictionaryStore = useDictionaryStore(); // 字典store

// ============ 响应式数据定义 ============

// 当前节点相关

interface CurrentNodeTask {
  deviceCode?: string;
  deviceName?: string;
  missionCode?: string;
  // 根据实际需要添加其他属性
}
interface Props {
  currentNodeTask?: CurrentNodeTask;
  type?: string;
}
// 使用 withDefaults 设置默认值
const props = withDefaults(defineProps<Props>(), {
  currentNodeTask: () => ({}),
  type: undefined
});
// 使用计算属性确保值的安全性
const safeCurrentNodeTask = computed(() =>
  props.currentNodeTask && typeof props.currentNodeTask === 'object'
    ? props.currentNodeTask
    : {}
);
const deviceCode = ref(safeCurrentNodeTask.value.deviceCode ?? '');
const currentNodeName = ref(safeCurrentNodeTask.value.deviceName ?? '');
const missionCode = ref(safeCurrentNodeTask.value.missionCode ?? '');



// 表格相关状态 - 使用useTable hook管理表格状态
const { tableRegister, tableState, tableMethods } = useTable({
  /**
   * 获取表格数据的API
   */
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState;

    // 如果没有选中设备节点，返回空数据
    if (!deviceCode.value || !missionCode.value) {
      return {
        list: [],
        total: 0,
      };
    }
    const collectorUserCode = localStorage.getItem("collectorUserCode");
    const res = await "/cDomesticComponents/page".get({
      deviceCode: deviceCode.value,
      missionCode: missionCode.value,
      isLockTask:1,
      createby: collectorUserCode || "",
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams),
    });
    return {
      list: res.data.records || [],
      total: res.data.total || 0,
    };
  },
});

// 解构表格状态和方法
const { total, loading, dataList, pageSize, currentPage } = tableState;
const { getList } = tableMethods;
// 监听 props 变化
watch(
  () => props.currentNodeTask,
  (newVal, oldVal) => {
    try {
      console.log(newVal, oldVal, "currentNodeTask");
      deviceCode.value = newVal?.deviceCode ?? '';
      currentNodeName.value = newVal?.deviceName ?? '';
      missionCode.value = newVal?.missionCode ?? '';


      // 只有在有设备代码时才调用 getList
      if (newVal?.deviceCode) {
        getList();
      }
    } catch (error) {
      console.error('Error in currentNodeTask watcher:', error);
      // ElMessage.error('数据加载失败');
    }
  },
  { immediate: true } // 添加 immediate 确保初始执行
);
// 搜索参数
const searchParams = ref({
  classificationCode: "",
});

// 对话框相关状态
const dialogVisible = ref(false); // 对话框显示状态
const dialogTitle = ref(""); // 对话框标题
const currentRow = ref(); // 当前操作的行数据
const actionType = ref(""); // 操作类型：'' | 'edit' | 'detail'



// ============ 计算属性 ============

// 类别选项
const classificationOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.COM_CLASSIFICATION
    ) || []
  );
});

// 自主可控等级选项
const controllableOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.INDEPENDENT_CONTROL_LEVEL
    ) || []
  );
});

// 是否核心关键元器件选项
const coreKeyOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(dictionaryStore.DICTIONARY_TYPES.YORN) ||
    []
  );
});

// 是否为WKB选项
const isWkbOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(dictionaryStore.DICTIONARY_TYPES.IS_WKB) ||
    []
  );
});

// ============ 监听器 ============

/**
 * 监听store中的currentNodeKey变化
 */


/**
 * 监听设备树节点变化，刷新表格数据
 */

/**
 * 监听当前树节点，更新节点名称
 */

// ============ 方法定义 ============




/**
 * 行操作处理（编辑/查看）
 * @param row 行数据
 * @param type 操作类型：'edit' | 'detail'
 */
const action = (row, type: string) => {
  dialogTitle.value = "查看";
  actionType.value = type;

  // 处理分类代码为空的情况
  row.classificationCode === undefined ||
  row.classificationCode == "" ||
  row.classificationCode == null
    ? (row.classificationCode = "")
    : row.classificationCode;

  // 根据分类代码长度构建级联选择器数据
  const data =
    row.classificationCode.length == 8
      ? [
          row.classificationCode.slice(0, 4) || "",
          row.classificationCode.slice(0, 6) || "",
          row.classificationCode || "",
        ]
      : row.classificationCode.length == 6
        ? [
            row.classificationCode.slice(0, 4) || "",
            row.classificationCode.slice(0, 6) || "",
          ]
        : [row.classificationCode.slice(0, 4) || ""];
  // 根据 deviceCode 查找设备名称
  const deviceName = findDeviceNameByCode(row.deviceCode);

  currentRow.value = {
    ...row,
    category: data,
   account: deviceName, // 使用查找到的设备名称
  };
  dialogVisible.value = true;
};

/**
 * 处理类别选择变化
 * @param value 选中的值数组
 */
const handleCategoryChange = (value) => {
  const selectedOptions = getCascaderObj(
    value,
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.COM_CLASSIFICATION
    )
  );

  if (!currentRow.value) {
    currentRow.value = {};
  }

  // 清空之前的分类数据
  currentRow.value.classification1 = "";
  currentRow.value.classification2 = "";
  currentRow.value.classification3 = "";
  currentRow.value.classificationCode = "";
  currentRow.value.category = value;
  currentRow.value.classificationCode =
    selectedOptions[selectedOptions.length - 1].code;

  // 根据选中的层级设置对应的分类字段
  if (selectedOptions.length > 0) {
    currentRow.value.classification1 = selectedOptions[0]?.text || "";
  }
  if (selectedOptions.length > 1) {
    currentRow.value.classification2 = selectedOptions[1]?.text || "";
  }
  if (selectedOptions.length > 2) {
    currentRow.value.classification3 = selectedOptions[2]?.text || "";
  }
};

/**
 * 工具函数：根据值和选项获取级联选择器对象
 * @param val 选中的值数组
 * @param opt 选项数组
 * @returns 选中的选项对象数组
 */
const getCascaderObj = (val, opt) => {
  return val.map(function (value, index, array) {
    for (var itm of opt) {
      if (itm.code == value) {
        opt = itm.children;
        return itm;
      }
    }
    return null;
  });
};

// 在子组件中添加这个方法
const findDeviceNameByCode = (deviceCode: string) => {
  console.log('deviceCode', deviceCode,props.currentNodeTask);

  if (!deviceCode || !props.currentNodeTask) return '';

  // 递归查找设备名称
  const findInTree = (nodes: any[]): string => {
    for (const node of nodes) {
      if (node.deviceCode === deviceCode) {
        return node.deviceName || '';
      }
      if (node.children && node.children.length > 0) {
        const result = findInTree(node.children);
        if (result) return result;
      }
    }
    return '';
  };

  return findInTree([props.currentNodeTask]);
};
// ============ CRUD表结构配置 ============

/**
 * 国产元器件管理表结构配置
 */
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: "selection",
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: "selection", hidden: true },
  },
  {
    field: "index",
    label: "序号",
    form: { hidden: true },
    search: { hidden: true },
    detail: { hidden: true },
    table: { type: "index" },
  },
  {
    field: "account",
    label: "所属设备",
    width: 90,
    search: { hidden: true },
    form: {
      component: "Input",
      value: currentNodeName.value,
      componentProps: {
        placeholder: "请输入所属设备",
        disabled: true,
      },
    },
    table: { hidden: true },
  },
  {
    field: "classificationCode",
    width: 100,
    label: "分类代码",
    form: {
      componentProps: {
        placeholder: "分类代码将自动生成",
        disabled: true,
      },
      formItemProps: { rules: [required()] },
    },
    search: { hidden: true },
  },
  {
    field: "category",
    label: "类别",
    width: 250,
    search: {
      component: "Cascader",

      componentProps: {
        placeholder: "类别",
        filterable: true,
        options: classificationOptions,
        props: {
          checkStrictly: false,
          emitPath: true,
          label: "text",
          value: "code",
        },
      },
    },
    form: {
      component: "Cascader",
      formItemProps: {
        rules: [{ required: true, message: "请选择类别" }],
      },
      componentProps: {
        placeholder: "请选择类别",
        filterable: true,
        options: classificationOptions,
        props: {
          checkStrictly: false,
          emitPath: true,
          label: "text",
          value: "code",
        },
        onChange: (value: any[]) => {
          handleCategoryChange(value);
        },
      },
    },
    detail: { hidden: true },
    table: {
      formatter: (row: any) => {
        // 组合分类字段，用 > 分隔，空值用 / 代替
        const parts = [
          row.classification1 || "/",
          row.classification2 || "/",
          row.classification3 || "/",
        ];
        if (row.classificationCode.length == 4) {
          return row.classification1;
        } else if (row.classificationCode.length == 6) {
          return row.classification1 + " > " + row.classification2;
        } else if (row.classificationCode.length == 8) {
          return parts.join(" > ");
        }
      },
    },
  },
  {
    field: "classification1",
    label: "一级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "classification2",
    label: "二级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "classification3",
    label: "三级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "componentName",
    label: "元器件名称",
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "元器件名称" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入元器件名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入元器件名称" },
        ],
      },
      componentProps: { placeholder: "请输入元器件名称" },
    },
  },
  {
    field: "modelSpecification",
    label: "型号规格",
    width: 120,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "型号规格" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入型号规格" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入型号规格" },
        ],
      },
      componentProps: { placeholder: "请输入型号规格" },
    },
  },
  {
    field: "manufacturer",
    label: "生产厂商",
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "生产厂商" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入生产厂商" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入生产厂商" },
        ],
      },
      componentProps: { placeholder: "请输入生产厂商" },
    },
  },
  {
    field: "qualityLevel",
    label: "质量等级",
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "质量等级" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入质量等级" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入质量等级" },
        ],
      },
      componentProps: { placeholder: "请输入质量等级" },
    },
  },
  {
    field: "independentControlLevel",
    label: "自主可控等级",
    width: 140,
    search: {
      component: "Select",
      label: "自主可控等级",
      hidden: false,
      componentProps: {
        placeholder: "自主可控等级",
        options: controllableOptions,
      },
    },
    form: {
      component: "Select",
      value: "",
      componentProps: { options: controllableOptions },
      formItemProps: {
        rules: [{ required: true, message: "请选择自主可控等级" }],
      },
    },
  },
  {
    field: "coreIndicators",
    label: "核心指标",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      colProps: { span: 24 },
      formItemProps: {
        rules: [
          { required: true, message: "请输入核心指标" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入核心指标" },
        ],
      },
    },
    detail: { span: 24 },
  },
  {
    field: "testingOrganization",
    label: "元器件检测机构",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    detail: { span: 24 },
    form: {
      component: "Input",
      componentProps: { placeholder: "请输入元器件检测机构" },
      colProps: { span: 24 },
      formItemProps: {
        rules: [
          { required: true, message: "请输入元器件检测机构" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入元器件检测机构" },
        ],
      },
    },
  },
  {
    field: "quantityPerDevice",
    label: "单个设备使用该产品数量",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入使用数量" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        placeholder: "请输入使用数量",
        type: "number",
        min: 0,
      },
    },
  },
  {
    field: "isCoreComponent",
    label: "是否核心关键元器件",
    width: 180,
    form: {
      component: "Select",
      value: "是",
      componentProps: { options: coreKeyOptions },
      formItemProps: {
        rules: [{ required: true, message: "请选择是否核心关键元器件" }],
      },
    },
    search: {
      component: "Select",
      label: "是否核心关键元器件",
      hidden: false,
      componentProps: {
        placeholder: "是否核心关键元器件",
        options: coreKeyOptions,
      },
    },
  },
  {
    field: "referencePrice",
    label: "参考价格(元)",
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入参考价格" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入参考价格",
        min: 0,
      },
    },
  },
  {
    field: "supplyCycle",
    label: "供货周期(周)",
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入供货周期" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入供货周期",
        min: 0,
      },
    },
  },
  {
    field: "historicalApplication",
    label: "历史应用信息",
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      colProps: { span: 24 },
      componentProps: {
        type: "textarea",
        rows: 3,
        placeholder: "请输入历史应用信息",
      },
    },
    detail: { span: 24 },
  },
  {
    field: "isWkb",
    label: "是否WKB",
    width: 90,
    form: {
      component: "Select",
      value: "",
      componentProps: { options: isWkbOptions },
      formItemProps: {
        rules: [{ required: true, message: "请选择是否WKB" }],
      },
    },
    search: { hidden: true },
    // table: { hidden: true },
  },
  {
    field: "isPre",
    label: "是否优选",
    width: 90,
    form: {
      hidden: true,
    },
    // table: { hidden: true },
    search: { hidden: true },
  },
  {
    field: "packagingType",
    label: "封装形式",
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入封装形式" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入封装形式" },
        ],
      },
      componentProps: { placeholder: "请输入封装形式" },
    },
  },
  {
    field: "personInCharge",
    label: "负责人",
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入负责人" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入负责人" },
        ],
      },
      componentProps: { placeholder: "请输入负责人" },
    },
  },
  {
    field: "contactInfo",
    label: "联系方式",
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      componentProps: { placeholder: "请输入联系方式" },
      formItemProps: {
        rules: [
          { required: true, message: "请输入联系方式" },
          { pattern: /^[0-9]{11}$/, message: "请输入正确的联系方式" },
        ],
      },
      colProps: { span: 12 },
    },
    detail: { span: 24 },
  },
  {
    field: "remarks",
    label: "备注",
    width: 90,
    search: { hidden: true },
    detail: { span: 24 },
    form: {
      component: "Input",
      componentProps: {
        type: "textarea",
        rows: 3,
        placeholder: "请输入备注信息",
      },
      colProps: { span: 24 },
    },
    table: { hidden: true },
  },
  {
    field: "action",
    label: "操作",
    fixed: "right",
    form: { hidden: true },
    detail: { hidden: true },
    search: { hidden: true },
    table: {
      width: 80,
      fixed: "right",
      slots: {
        default: (data: any) => {
          const row = data.row;
          return (
            <>
              <div style="display:flex;color: var(--el-color-primary)">
                <div
                  class="flex-1 cursor-pointer"
                  onClick={() => action(row, "detail")}
                >
                  <el-icon>
                    <View />
                  </el-icon>
                  查看
                </div>
              </div>
            </>
          );
        },
      },
    },
  },
]);

// 使用CRUD Schemas hook
const { allSchemas } = useCrudSchemas(crudSchemas);

// ============ 生命周期 ============

/**
 * 组件挂载时初始化
 */
onMounted(async () => {
  // 检查是否有有效数据
  if (safeCurrentNodeTask.value.deviceCode && safeCurrentNodeTask.value.missionCode) {
    getList();
  }
});

</script>

<style scoped lang="less">
:deep(.el-divider--horizontal) {
  margin: 5px 0 15px 0;
}

.mb-10px {
  display: flex;
}

.opBtn-upload {
  display: inline-block;
  margin: 0 12px;
}
:deep(.el-card__body ){
  padding: 10px  0 !important;
}
</style>
